<?php
// vim: fdm=marker
/**
 * 数据库备份脚本
 */
/*
 * crontab -e
 * 0       4     *       *       *       /usr/local/php5/bin/php /web/newad/_=tool3298/pg_bak.php
 */
date_default_timezone_set('PRC');

/**
 * removeDir
 * 删除目录
 *
 * @param mixed $dirName
 * @return void
 */
function removeDir($dirName) {/*{{{*/
    $result = false;

    if(!is_dir($dirName)) {
        return false;
    }

    $handle = opendir($dirName);

    while(($file = readdir($handle)) !== false) {
        if($file != '.' && $file != '..') {
            $dir = $dirName . DIRECTORY_SEPARATOR . $file;
            is_dir($dir) ? removeDir($dir) : unlink($dir);
        }
    }

    closedir($handle);

    $result = rmdir($dirName) ? true : false;

    return $result;
}/*}}}*/

$bakRootDir = '/bak/db';
$bakDir     = $bakRootDir . '/' . date('j');

removeDir($bakDir); //先删除今天对应的已存在的备份
mkdir($bakDir);

$waitBakSchema = array(
                    'public', 
                    'd' . date('Ymd', strtotime('-1 day')),
                    'm' . date('Ym'),
                 );   //待备份的模式名称
$prevMonthSchema = 'm' . date('Ym', strtotime('-3 day'));   //-3 day是为了多保留几天上月按月保存的数据

if(!in_array($prevMonthSchema, $waitBakSchema)) {
    $waitBakSchema[] = $prevMonthSchema;
}

$dbUser = 'zlink';
$dbPwd  = 'abc123';
$dbName = 'newad';

$cmd = "/usr/local/bin/pg_dump "
     . "--username {$dbUser} "
     . "--no-privileges "
     . "--no-tablespaces "
     . "--no-unlogged-table-data "
     . "--schema {schemaName} "
     . "{$dbName} "
     . "> {bakFile}";

$desc = array(
    0 => array('pipe', 'r'),
    1 => array('pipe', 'w'),
    2 => array('pipe', 'w'),
);
$env = array('PGPASSWORD' => $dbPwd);

foreach($waitBakSchema as $v) {
    $tmpBakFile = "{$bakDir}/{$v}.bak";
    $tmpCmd     = str_replace(array('{schemaName}', '{bakFile}'), array($v, $tmpBakFile), $cmd);

    if(!$process = proc_open($tmpCmd, $desc, $pipes, NULL, $env)) {
        echo $tmpCmd . " Run Error\n";

        continue;
    }

    $s    = stream_get_contents($pipes[2]);
    $msg  = "Bakup {$dbName}.{$v} To {$tmpBakFile} ";
    $msg .= empty($s) ?   'OK'  :   'ERROR ' . $s;

    echo $msg . "\n";
}
